import { defineStore } from 'pinia'


function saveToLocalStorage(tags) {

    localStorage.setItem('tagsView', JSON.stringify(tags))
}

function getFromLocalStorage() {
    let cachedTagsView = localStorage.getItem('tagsView')
    if(cachedTagsView) {
        return JSON.parse(cachedTagsView)
    }
}

function clearLocalStorage() {
    localStorage.removeItem('tagsView')
}

export default defineStore('tagsView', {
    state: ()=> {
        return {
            tags: getFromLocalStorage() || [
                {
                    title: '主页',
                    name: 'home',
                    path: '/home',
                    isActive: false
                }
            ],
        }
    },
    getters: {

    },
    actions: {
        doOnrouteChange(route) {
            // debugger
            // console.log('doOnrouteChange->新路由', route);
            let currRouteName = route.name
            let tagNameArr = []
            let flag = false
            this.tags.forEach(tag=>{
                tag.isActive = false
                if(tag.name == currRouteName) {
                    flag = true
                    tag.isActive = true
                    tag.query = route.query,
                    tag.params = route.params,
                    tag.fullPath = route.fullPath
                }
            })       
            if(!flag) {
                // console.log('原先没有这个路由,现在添加tag', route.name);
                this.tags.push({
                    title: route.meta.title,
                    name: route.name,
                    path: route.path,
                    isActive: true,
                    query: route.query,
                    params: route.params,
                    fullPath: route.fullPath
                })
            }  
            saveToLocalStorage(this.tags)   
        },
        closeSpecifiedTag(tag){
            // debugger
            let index = -1;
            for(let i=0;i<this.tags.length;i++) {
                if(this.tags[i].name === tag.name) {
                    index = i
                    break
                }
            }
            if(index > -1) {
                this.tags.splice(index,1)
            }
            saveToLocalStorage(this.tags)   
        },
        selectSpecifiedTag(tag) {
            // debugger
            this.tags.forEach(t=>{
                t.isActive = false
                if(t.name == tag.name) {
                    t.isActive = true
                }
            })  
            saveToLocalStorage(this.tags)   
        },
        resetTagsView() {
            this.tags =[
                {
                    title: '主页',
                    name: 'home',
                    path: '/home',
                    isActive: false
                }
            ]
            clearLocalStorage()
        }
    }
})